<!--
 * @Author: WeijianXu weijian.xu@unidt.com
 * @Date: 2023-05-19 11:16:07
 * @LastEditors: WeijianXu weijian.xu@unidt.com
 * @LastEditTime: 2024-05-30 14:04:11
 * @FilePath: \front-end-of-task-center\src\components\TagSelect\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="un-tag-select">
    <el-tag v-for="item in options" :key="item"
      :type="selected.indexOf(item) !== -1 ? 'primary' : 'info'"
      :effect="selected.indexOf(item) !== -1 ? 'dark' : 'plain'" @click="toggleSelect(item)">
      {{ item }}{{ suffix }}
    </el-tag>
  </div>
</template>

<script>
import isEqual from "lodash/isEqual";

export default {
  props: {
    value: {
      type: [Array, String, Number],
      default() {
        return [];
      },
    },
    options: {
      type: Array,
      default() {
        return [];
      },
    },
    // 是否多选
    multi: {
      type: Boolean,
      default: false,
    },
    // 是否点选取消
    clearable: Boolean,
    suffix: String,
  },
  data() {
    return {
      selected: [],
    };
  },
  created() {
    this.setSelected(this.value);
  },
  watch: {
    /* options: {
      deep: true,
      handler: function (val) {
        this.tags.set(val);
      },
    }, */
    value: {
      deep: true,
      handler: function (val) {
        this.setSelected(val);
      },
    },
  },
  methods: {
    setSelected(val) {
      this.selected =
        Array.isArray(val) && !isEqual(val, this.selected) ? val : [val];
    },
    toggleSelect(val) {
      const idx = this.selected.indexOf(val);
      if (idx !== -1) {
        if (this.clearable) {
          this.selected.splice(idx, 1);
        }
      } else if (this.multi) {
        this.selected.push(val);
      } else {
        this.selected[0] = val;
      }

      const currSelected = this.multi ? this.selected : this.selected[0];
      this.$emit("input", currSelected);
      this.$emit("change", currSelected);
    },
  },
};
</script>

<style lang="scss">
.un-tag-select {
  display: flex;
  align-items: center;

  .el-tag {
    cursor: pointer;
    min-width: 60px;
    text-align: center;

    +.el-tag {
      margin-left: 10px;
    }
  }
}
</style>
